import { Spin } from 'antd';
import { connect } from 'umi';
import uuid from 'es6-uuid';
import _ from 'lodash';
import moment from 'moment';
import React from 'react';
import contant from './contant';
import { AdvancedSearch, DATA_ENTRY, ContentPackage, TableC, QuickQueryC, SecondHeaderC, XYAxisChartsC } from '@/src/components';
import { getTextWidth } from '@/src/utils/utils';
import DimensionCustomization from './dimensionCustomization';
import styles from './index.less';
import { reservedBits } from '@/src/utils/commonFunc';

@connect(({ loading, creditSpreadAnalysisM, addressM: { province }, globalM }) => ({
  loading,
  creditSpreadAnalysisM,
  provinceData: [{ title: '全国', value: '全国', children: province }],
  globalM,
}))
export default class creditSpreadAnalysis extends React.Component {
  state = {
    dataSource: [], // 选中分析维度为非自定义列表数据
    customizateDataSource: [], // 选中分析维度为自定义列表数据
    tradingDate: moment(), // 银行间前一交易日
    radioVal: '1', // tab value
    creditOrChange: '1', // 信用利差 | 利差变动
    dimension: '1', // 分析维度 默认评级
    cityRange: undefined, // 城市
    date: undefined, // 日期
    subjectRating: '全部', // 主体评级
    remainingTerm: '全部', // 剩余期限
    executiveLevel: '全部', // 行政级别
    defaultSelect: undefined, // 默认选中的行id
    xAxis: [], // charts xAxis
    series: [], // charts series
    spinStatus: false, // charts loading
    sortedInfo: {}, // 排序对象
    isCustomization: true, // 分析维度选中自定义
    moreSearchCondition: true, // 分析维度选中自定义时候 显示隐藏新的查询条件
  };

  refIns = React.createRef();

  refDimenSion = React.createRef();

  initSearchCondition = (searchCondition) => {
    this.setState({ ...searchCondition, tradingDate: searchCondition.date }, () => this.getInfoForTable());
  };

  componentDidMount() {
    // 没有读到 走默认查询流程
    const creditSpreadAnalysisSearchInfo = localStorage.getItem(`creditSpreadAnalysisSearch${localStorage.getItem('antd-pro-userId')}`);
    if (!creditSpreadAnalysisSearchInfo || creditSpreadAnalysisSearchInfo === 'null') {
      this.getTradeDay(); // 获取银行间前一交易日 |  QuickQueryC调用了onchange ，getInfoForTable
    } else {
      // 读到查询数据使用查询数据
      const searchCondition = JSON.parse(localStorage.getItem(`creditSpreadAnalysisSearch${localStorage.getItem('antd-pro-userId')}`));
      this.setState({ moreSearchCondition: searchCondition?.dimension !== '4', isCustomization: searchCondition?.dimension !== '4' }, () => {
        this.initSearchCondition(searchCondition);
      });
    }
    this.props.dispatch({ type: 'addressM/getLocation' }); // 获取地区
  }

  // 获取银行间前一交易日
  getTradeDay = (resetPayload = {}) => {
    this.props.dispatch({
      type: `creditSpreadAnalysisM/getBankTradingDate`,
      payload: { type: '2' },
      callback: (res) => {
        this.setState(
          {
            ...resetPayload,
            tradingDate: moment(res).format('YYYY-MM-DD'),
            date: moment(res).format('YYYY-MM-DD'),
          },
          () => {
            this.getInfoForTable();
          },
        );
      },
    });
  };

  // 查询
  searchDocker = (e) => {
    this.refDimenSion.current?.resetRefIns(); // 重置状态
    const { tradingDate } = this.state;
    if (!e) {
      const resetPayload = {
        date: moment(tradingDate).format('YYYY-MM-DD'),
        dimension: '1',
        cityRange: undefined,
        xAxis: [], // charts xAxis
        series: [], // charts series
        spinStatus: false,
        sortedInfo: {}, // 排序对象
        radioVal: '1', // tab value
        isCustomization: true,
        moreSearchCondition: true,
        subjectRating: undefined, // 主体评级
        remainingTerm: undefined, // 剩余期限
        executiveLevel: undefined, // 行政级别
      };
      this.getTradeDay(resetPayload);
      return;
    }
    const payload = {
      ...e,
      date: moment(e.date).format('YYYY-MM-DD'),
      isCustomization: e?.dimension !== '4', // 查询判断显示内容
    };
    this.setState(payload, () => this.getInfoForTable());
  };

  // 获取列表数据
  getInfoForTable = () => {
    const { dimension, cityRange, radioVal, creditOrChange, date, executiveLevel, remainingTerm, subjectRating, moreSearchCondition } = this.state;
    const obj = {};
    if (this.state.sortedInfo?.order) {
      obj.columnKey = this.state.sortedInfo?.columnKey;
      obj.order = this.state.sortedInfo?.order;
    }
    const payload = {
      date: moment(date).format('YYYY-MM-DD'),
      dimension,
      cityRange: cityRange ? (cityRange.length === 0 ? undefined : cityRange) : cityRange,
      executiveLevel: moreSearchCondition ? undefined : executiveLevel,
      remainingTerm: moreSearchCondition ? undefined : remainingTerm,
      subjectRating: moreSearchCondition ? undefined : subjectRating,
      creditOrChange: moreSearchCondition ? undefined : creditOrChange,
      rateDiff: this.refIns.current ? '1' : radioVal,
      ...obj,
    };
    localStorage.setItem(
      `creditSpreadAnalysisSearch${localStorage.getItem('antd-pro-userId')}`,
      JSON.stringify({
        date: moment(date).format('YYYY-MM-DD'),
        dimension,
        cityRange: cityRange ? (cityRange.length === 0 ? undefined : cityRange) : cityRange,
        executiveLevel: moreSearchCondition ? undefined : executiveLevel,
        remainingTerm: moreSearchCondition ? undefined : remainingTerm,
        subjectRating: moreSearchCondition ? undefined : subjectRating,
      }),
    );
    this.props.dispatch({
      type: `creditSpreadAnalysisM/querySpreadAnalysis`,
      payload,
      callback: (res) => {
        const { dataSource } = res;
        console.log('dataSource father', dataSource);
        dataSource.map((v) => {
          if (v.city === 'null') v.city = null;
        });
        this.setState(
          {
            dataSource,
            customizateDataSource: moreSearchCondition ? [] : dataSource, // 防止把分析维度选不是自定义获取的数据传到了子组件内
            defaultSelect: dataSource.length > 0 ? dataSource[0][radioVal === '1' ? 'province' : 'city'] : undefined,
          },
          () => {
            if (dataSource.length > 0) {
              this.getRegionalCreditSpreadCharts(dataSource[0]);
            } else {
              this.setState({
                xAxis: [null],
              });
            }
          },
        );
      },
    });
  };

  // 设置高亮类名
  setRowClass = (record) => ((this.state.radioVal === '1' ? record.province : record.city) === this.state.defaultSelect ? 'defaultSelect' : '');

  // 切换tab
  onChangeRadio = (radioVal) => {
    const preRadioVal = this.state.radioVal; // 切换时需要重置
    this.setState({ sortedInfo: {}, radioVal }, () => {
      if (radioVal !== preRadioVal) {
        this.getInfoForTable(); // 首次不执行
      }
    });
  };

  /**
   * 点击列表获取走势图数据
   * @param record
   */
  getRegionalCreditSpreadCharts = (record) => {
    const { dimension, moreSearchCondition, creditOrChange, executiveLevel, remainingTerm, subjectRating } = this.state;
    const { dispatch } = this.props;
    this.setState({ spinStatus: true });
    const payload = {
      executiveLevel: moreSearchCondition ? undefined : executiveLevel,
      remainingTerm: moreSearchCondition ? undefined : remainingTerm,
      subjectRating: moreSearchCondition ? undefined : subjectRating,
      province: record.province,
      city: record.city,
      dimension,
      creditOrChange: moreSearchCondition ? undefined : creditOrChange,
      date: moment(this.state.date).format('YYYY-MM-DD'),
    };
    if (payload.city === null || payload.city === undefined) delete payload.city;
    dispatch({
      type: 'creditSpreadAnalysisM/getRegionalCreditSpreadChart',
      payload,
      callback: (data) => {
        const resSeries = data.series.map((v) => {
          const needData = v.data;
          return {
            name: v.name,
            data: needData.map((i) => (i ? reservedBits(i) : i)),
          };
        });
        this.setState({
          xAxis: data.xAxis ?? [null],
          series: resSeries ?? [null],
          spinStatus: false,
        });
      },
    });
  };

  handleClickRow = (
    record, // 表格行点击事件
  ) => ({
    onClick: () => {
      const { radioVal } = this.state;
      this.setState({ defaultSelect: radioVal === '1' ? record.province : record.city }, () => this.getRegionalCreditSpreadCharts(record));
    },
  });

  handleTableChange = (pagination, filter, sorter) => {
    this.setState({ sortedInfo: sorter }, () => {
      this.getInfoForTable();
    });
  };

  /**
   * 信用利差 | 利差变动 切换, 省级 | 市级 切换
   * @param value （查询的参数值）
   * @param tabType （信用利差 | 利差变动）还是（省级 | 市级）
   */
  onTabChange = (value, tabType) => {
    if (tabType === 'tabLeft') {
      // 信用利差 | 利差变动 切换
      this.setState({ creditOrChange: value }, () => {
        this.getInfoForTable();
      });
    }
    if (tabType === 'tabRight') {
      this.refIns.current = undefined; // 切换省市恢复
      // 省级 | 市级 切换
      this.setState({ radioVal: value }, () => {
        this.getInfoForTable();
      });
    }
  };

  // 分析维度选中自定义时的列表的点击行
  onClickRow = (sonCompRecord) => this.getRegionalCreditSpreadCharts(sonCompRecord);

  render() {
    const {
      loading,
      creditSpreadAnalysisM: { columns = [] },
      provinceData,
      globalM: {
        dataDictionary: { InvestmentBndCreditSpreadAnalysisType = [] },
      },
    } = this.props;
    const {
      customizateDataSource,
      dataSource = [],
      tradingDate,
      radioVal,
      series,
      xAxis,
      spinStatus,
      sortedInfo,
      isCustomization,
      moreSearchCondition,
      subjectRating,
      remainingTerm,
      executiveLevel,
      cityRange,
    } = this.state;
    const dimensionArr = InvestmentBndCreditSpreadAnalysisType.map((v) => ({ value: v.code, title: v.value })); // 获取分析维度下拉
    const dimensionArrSorted = [dimensionArr[2], dimensionArr[3], dimensionArr[0], dimensionArr[1]];
    let columnsIntoAttribute = _.cloneDeep(columns); // column插入 width， sorter， align
    const intoWithAndSorter = (arr = []) => {
      arr.map((value) => {
        if (value.children) intoWithAndSorter(value.children);
        if (value.key) {
          value.width = 100;
          value.sorter = true;
          value.sortOrder = sortedInfo?.columnKey === value.key && sortedInfo?.order;
          value.align = 'center';
        }
        if (value.key === null) value.align = 'center';
        if (['creditSpreads_nationalZone', 'creditSpreadsQuantiles_nationalZone', 'creditSpreadsQuantiles_provinceZone', 'creditSpreads_provinceZone'].includes(value.key)) {
          value.width = 140;
        }
        // fix: 返回值保留小数尾数为0时后端会自动舍弃
        if (value.key !== 'province' && value.key !== 'city' && value.key !== null) {
          value.render = (text) => {
            if (text === null) return '--';
            return reservedBits(text);
          };
        }
        // 省市不排序
        if (['province', 'city'].includes(value.key)) delete value.sorter;
      });
      return arr;
    };
    columnsIntoAttribute = intoWithAndSorter(columnsIntoAttribute);
    let legendWidth = 0; // 图列总宽度
    series.map((v) => (legendWidth += getTextWidth(v.name ?? '')));
    const target = document.querySelector('#RegionalLine');
    const targetWidth = target?.clientWidth; // 图标总宽度
    return (
      <ContentPackage
        title='城投债信用利差分析'
        contentHtml={
          <div className={styles.creditSpreadAnalysis}>
            <AdvancedSearch
              onQuery={(e) => this.searchDocker(e)}
              onClear={(e) => this.searchDocker(e)}
              dataSource={[
                {
                  dataIndex: 'date',
                  title: '分析日期',
                  type: DATA_ENTRY.SINGLEDATE,
                  initialValue: moment(tradingDate),
                  disableEnd: moment(),
                  allowClear: false,
                },
                {
                  dataIndex: 'cityRange',
                  title: '城市范围',
                  type: DATA_ENTRY.TREESELECT,
                  dataSource: provinceData || [],
                  treeDefaultExpandAll: true,
                  initialValue: cityRange,
                  treeCheckable: true,
                  placeholder: '请选择',
                  allowClear: true,
                  showSearch: true,
                  isMultiple: true,
                  onChange: (e) => this.setState({ cityRange: e }),
                },
                {
                  dataIndex: 'dimension',
                  title: '分析维度',
                  type: DATA_ENTRY.SELECT,
                  initialValue: this.state.dimension,
                  dataSource: [...dimensionArrSorted],
                  placeholder: '请选择',
                  allowClear: true,
                  onChange: (value) => {
                    if (value === '4') {
                      this.refIns.current = true;
                      this.setState({ moreSearchCondition: false, subjectRating: '全部', remainingTerm: '全部', executiveLevel: '全部' });
                    } else {
                      this.refIns.current = undefined;
                      this.setState({ moreSearchCondition: true, subjectRating: undefined, remainingTerm: undefined, executiveLevel: undefined, radioVal: '1' });
                    }
                  },
                },
                {
                  hide: moreSearchCondition,
                  dataIndex: 'subjectRating',
                  title: '主体评级',
                  type: DATA_ENTRY.SELECT,
                  initialValue: subjectRating,
                  dataSource: contant.subjectRating || [],
                  placeholder: '请选择',
                  positionBody: true,
                  allowClear: true,
                },
                {
                  hide: moreSearchCondition,
                  dataIndex: 'remainingTerm',
                  title: '剩余期限',
                  type: DATA_ENTRY.SELECT,
                  initialValue: remainingTerm,
                  dataSource: contant.remainingTerm || [],
                  placeholder: '请选择',
                  allowClear: true,
                },
                {
                  hide: moreSearchCondition,
                  dataIndex: 'executiveLevel',
                  title: '行政级别',
                  type: DATA_ENTRY.SELECT,
                  initialValue: executiveLevel,
                  dataSource: contant.executiveLevel || [],
                  placeholder: '请选择',
                  allowClear: true,
                },
              ]}
            />
            {!isCustomization ? (
              <DimensionCustomization dataSource={customizateDataSource} onTabChange={this.onTabChange} onClickRow={this.onClickRow} ref={this.refDimenSion} />
            ) : (
              <>
                <div className={styles.modes}>
                  <QuickQueryC
                    dataSource={[
                      { value: '1', title: '省级利差' },
                      { value: '2', title: '市级利差' },
                    ]}
                    initialValue={radioVal}
                    onChange={(e) => this.onChangeRadio(e)}
                  />
                </div>
                <div>
                  <TableC
                    columns={columnsIntoAttribute || []}
                    loading={loading.effects[`creditSpreadAnalysisM/querySpreadAnalysis`]}
                    dataSource={dataSource || []}
                    scroll={{ x: 'max-content', y: 410 }}
                    rowKey={`${uuid(32)}-city`}
                    rowClassName={this.setRowClass}
                    hidePage={true}
                    onRow={this.handleClickRow}
                    selfScrollY={true}
                    onChange={this.handleTableChange}
                    size='small'
                  />
                </div>
              </>
            )}
            <div className={styles.charts} id='RegionalLine'>
              <SecondHeaderC title='区域信用利差走势图' />
              <Spin spinning={spinStatus}>
                <XYAxisChartsC
                  series={xAxis[0] === null ? [] : series}
                  xAxis={xAxis}
                  yAxisUnit={['信用利差(bp)']}
                  height={400}
                  type='line'
                  dataZoom={true}
                  legendType={legendWidth > targetWidth ? 'scroll' : 'plain'}
                />
              </Spin>
            </div>
          </div>
        }
      />
    );
  }
}
